package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

func main() {
	// 编码至json
	encode()

	// 解码至struct
	decode()

	readJsonFromFile()
}

// Create a struct to match the format of JSON
type Person struct {
	Name string `json:"username"`
	City string `json:"municipality"`
}

func decode() {
	json_str := `{ "Name": "大柱", "City": "北京"}`
	var p Person

	if err := json.Unmarshal([]byte(json_str), &p); err != nil {
		fmt.Println("Error parsing JSON: ", err)
	}

	// output result
	fmt.Printf("Name: %v, City: %v\n", p.Name, p.City)
}

func encode() {

	p := Person{Name: "二狗", City: "Nanjing"}

	data, err := json.Marshal(p)
	if err != nil {
		fmt.Println("JSON Encoding Error", err)
	}

	fmt.Printf("%s", data)

	// 格式化输出
	data2, err := json.MarshalIndent(p, "", "  ")
	if err != nil {
		fmt.Println("JSON Encoding Error", err)
	}

	fmt.Printf("\n%s\n", data2)
}

func readJsonFromFile() {
	var people []Person
	filename := "G:\\workspace_gitee\\golang\\golang-web\\test\\names.json"
	file, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("Error reading file")
	}

	// the names.json file has an array of person objects, so read into people
	if err := json.Unmarshal(file, &people); err != nil {
		fmt.Println("Error parsing JSON", err)
	}

	// output result
	fmt.Println(people)
}
